package com.controller;

import com.annotation.IgnoreAuth;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.entity.ChapterEntity;
import com.entity.LessonEntity;
import com.service.ChapterService;
import com.service.LessonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * AI服务控制类
 */
@RestController
@RequestMapping("/api/ai")
public class AiController {

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private LessonService lessonService;
    private final RestTemplate restTemplate;
    private final String aiDocxServiceUrl = "http://localhost:9000/ai/export/docx";

    private final String aiPDFServiceUrl = "http://localhost:9000/ai/export/pdf";

    private final String aiService= "http://localhost:9000/ai/v1/chat/completions";

    public AiController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }


    /**
     * 前端调用此接口，Spring Boot 代理请求给 AI 服务，并将 AI 服务返回的文件转发给前端。
     *
     * @param requestPayload 接收前端发送的 JSON 请求体，包含 content 和 filename
     * @return ResponseEntity<byte[]> 包含文件内容的响应
     */
    @PostMapping("/generateAiContentByChapter")
    public ResponseEntity<byte[]> generateDocxByChapter(@RequestHeader("Token") String token, @RequestBody Map<String, Long> requestPayload) {
        Long chapterId = requestPayload.get("chapterId");
        Long type=requestPayload.get("type");
        if (chapterId == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        ChapterEntity chapter=chapterService.selectById(chapterId);
        String filenameToPassToAi=chapter.getTitle();
        String contentToPassToAi=lessonService.getCombinedContentForAiByChapterId(chapterId);

        //如果知识库里面没东西，就返回一个定制的error
        try {
            if (contentToPassToAi == null || contentToPassToAi.isEmpty()) {
                HttpHeaders errorHeaders = new HttpHeaders();
                errorHeaders.add("X-Error-Message", "No content for Ai");
                return new ResponseEntity<>(new byte[0], errorHeaders, HttpStatus.BAD_REQUEST);
            }

            Map<String, String> aiServicePayload = new HashMap<>();
            aiServicePayload.put("content", contentToPassToAi);
            aiServicePayload.put("filename", filenameToPassToAi);

            HttpHeaders aiRequestHeaders = new HttpHeaders();

            // 在请求头中添加token已确认能正确将请求转发至网关
            aiRequestHeaders.set("Token", token);

            aiRequestHeaders.setContentType(MediaType.APPLICATION_JSON);

            HttpEntity<Map<String, String>> aiRequestEntity = new HttpEntity<>(aiServicePayload, aiRequestHeaders);

            String url;
            if(type==1){
                url=aiDocxServiceUrl;
            }
            else{
                url=aiPDFServiceUrl;
            }
            ResponseEntity<byte[]> aiResponse = restTemplate.postForEntity(
                    url,
                    aiRequestEntity,
                    byte[].class
            );

            if (aiResponse.getStatusCode().is2xxSuccessful() && aiResponse.hasBody()) {
                HttpHeaders responseToFrontendHeaders = new HttpHeaders();

                MediaType aiContentType = aiResponse.getHeaders().getContentType();
                if (aiContentType != null) {
                    responseToFrontendHeaders.setContentType(aiContentType);
                } else {
                    if(type==1){
                        responseToFrontendHeaders.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.wordprocessingml.document"));
                    }
                    else{
                        responseToFrontendHeaders.setContentType(MediaType.parseMediaType("application/pdf"));
                    }
                }

                //设置content-disposition，和生成的文件的名字有关
                String aiContentDisposition = aiResponse.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
                if (aiContentDisposition != null) {
                    responseToFrontendHeaders.set(HttpHeaders.CONTENT_DISPOSITION, aiContentDisposition);
                } else {
                    responseToFrontendHeaders.setContentDispositionFormData("attachment", filenameToPassToAi);
                }

                responseToFrontendHeaders.setContentLength(aiResponse.getBody().length);

                return new ResponseEntity<>(aiResponse.getBody(), responseToFrontendHeaders, HttpStatus.OK);

            } else {
                return new ResponseEntity<>(HttpStatus.BAD_GATEWAY);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


    @PostMapping("/generateTestPaper")
    public ResponseEntity<byte[]> generateTestPaper(@RequestHeader("Token") String token, @RequestBody Map<String, Long> requestPayload) {
        Long chapterId = requestPayload.get("chapterId");
        Long type = requestPayload.get("type");

        if (chapterId == null) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        ChapterEntity chapter = chapterService.selectById(chapterId);
        String filenameToPassToAi = chapter.getTitle();

        //这个值用来传递给ai，让它生成试卷的文本形式
        String contentToPassToAi ="请根据我提供的“课程资料”，为用户生成两份测验试卷，两份试卷题目要相同，但第一份只有题目，第二份除了题目还有答案和解析，要求每种类型的题目至少生成5个。\n" +
                "\n" +
                "**【输出规则】**\n" +
                "你必须严格、精确地遵循下面的模板格式，不允许添加、修改或删除任何标记（如`**`符号）。尤其是“选项”部分，必须使用嵌套的项目符号列表。\n" +
                "\n" +
                "**【格式模板】**\n" +
                "\n" +
                "---\n" +
                "\n**题型**: 单选题\n" +
                "\n**题干**: (这里写题干)\n" +
                "\n**选项**:\n" +
                "\nA. (选项A内容)\n" +
                "\nB. (选项B内容)\n" +
                "\nC. (选项C内容)\n" +
                "\nD. (选项D内容)\n" +
                "\n**答案**: (只写字母, 例如: A)\n" +
                "\n**解析**: (写解析)\n" +
                "\n" +
                "---\n" +
                "\n**题型**: 判断题\n" +
                "\n**题干**: (这里写题干)\n" +
                "\n**答案**: (只写 正确 或 错误)\n" +
                "\n**解析**: (写解析)\n" +
                "\n" +
                "---\n" +
                "\n**题型**: 简答题\n" +
                "\n**题干**: (这里写题干)\n" +
                "\n**参考答案**: (写参考答案)\n" +
                "\n" +
                "---" +
                "以下是我提供给你的课程资料："+ lessonService.getCombinedContentForAiByChapterId(chapterId);


        try {
            //如果知识库里面没东西，就返回一个定制的error
            if (contentToPassToAi == null || contentToPassToAi.isEmpty()) {
                HttpHeaders errorHeaders = new HttpHeaders();
                errorHeaders.add("X-Error-Message", "No content for Ai");
                return new ResponseEntity<>(new byte[0], errorHeaders, HttpStatus.BAD_REQUEST);
            }

            Map<String, Object> aiServicePayload = new HashMap<>();
            aiServicePayload.put("model", "gemini-1.5-flash-latest");
            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", contentToPassToAi);
            messages.add(message);

            aiServicePayload.put("messages", messages);

            aiServicePayload.put("stream", false);

            HttpHeaders aiHeaders = new HttpHeaders();

            // 在请求头中添加token已确认能正确将请求转发至网关
            aiHeaders.set("Token", token);

            aiHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> aiRequestEntity = new HttpEntity<>(aiServicePayload, aiHeaders);

            ResponseEntity<Map> aiTextResponse = restTemplate.postForEntity(
                    aiService,
                    aiRequestEntity,
                    Map.class);

            if (!aiTextResponse.getStatusCode().is2xxSuccessful() || aiTextResponse.getBody() == null) {
                return new ResponseEntity<>(HttpStatus.BAD_GATEWAY);
            }

            // 提取AI返回的试卷文本
            Map<String, Object> aiResponseBody = aiTextResponse.getBody();
            String contentForTestPaper = extractTextFromAiResponse(aiResponseBody);
            if (contentForTestPaper == null || contentForTestPaper.trim().isEmpty()) {
                return new ResponseEntity<>(HttpStatus.NO_CONTENT);
            }

            //请求PDF服务生成试卷文件
            Map<String, Object> pdfPayload = new HashMap<>();
            pdfPayload.put("content", contentForTestPaper);
            pdfPayload.put("filename", filenameToPassToAi);

            HttpHeaders pdfHeaders = new HttpHeaders();

            pdfHeaders.set("Token", token);

            pdfHeaders.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<Map<String, Object>> pdfRequestEntity = new HttpEntity<>(pdfPayload, pdfHeaders);

            ResponseEntity<byte[]> pdfResponse = restTemplate.postForEntity(aiPDFServiceUrl, pdfRequestEntity, byte[].class);

            if (pdfResponse.getStatusCode().is2xxSuccessful() && pdfResponse.hasBody()) {
                HttpHeaders responseHeaders = new HttpHeaders();

                responseHeaders.setContentType(MediaType.APPLICATION_PDF);


                responseHeaders.setContentDispositionFormData("attachment", filenameToPassToAi + (".pdf"));
                responseHeaders.setContentLength(pdfResponse.getBody().length);

                return new ResponseEntity<>(pdfResponse.getBody(), responseHeaders, HttpStatus.OK);
            } else {
                return new ResponseEntity<>(HttpStatus.BAD_GATEWAY);
            }

        } catch (Exception e) {
            e.printStackTrace();
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }



    /**
     *将ai返回的内容转成字符串
     */
    private String extractTextFromAiResponse(Map<String, Object> aiResponseBody) {
        try {
            List<Map<String, Object>> choices = (List<Map<String, Object>>) aiResponseBody.get("choices");
            if (choices != null && !choices.isEmpty()) {
                Map<String, Object> message = (Map<String, Object>) choices.get(0).get("message");
                if (message != null) {
                    return (String) message.get("content");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
